package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"new_ginblog/internal/models"
	"new_ginblog/internal/repositories"
	"new_ginblog/internal/utils/errormsg"
	"strconv"
)

var (
	statusCode int
)

// AddUser 添加用户
func AddUser(c *gin.Context) {
	var user models.User
	_ = c.ShouldBindJSON(&user)

	statusCode = repositories.CheckUser(user.Username)

	if statusCode == errormsg.ERROR_USERNAME_OK {
		statusCode = errormsg.SUCCESS
		repositories.AddUser(&user)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": statusCode,
		"msg":  errormsg.GetErrorMsg(statusCode),
		"data": user,
	})
}

// GetUser 获取用户列表
func GetUser(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	data, code, total := repositories.GetUser(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"code":  code,
		"msg":   errormsg.GetErrorMsg(code),
		"users": data,
		"total": total,
	})
}

// DeleteUser 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	statusCode := repositories.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"code": statusCode,
		"msg":  errormsg.GetErrorMsg(statusCode),
	})
}

// UpdateUser 修改用户数据
func UpdateUser(c *gin.Context) {
	var user *models.User
	_ = c.ShouldBindJSON(&user)

	statusCode = repositories.CheckUser(user.Username)
	if statusCode == errormsg.ERROR_USERNAME_USED {
		c.JSON(http.StatusOK, gin.H{
			"code": statusCode,
			"msg":  errormsg.GetErrorMsg(statusCode),
		})
		c.Abort()
		return
	}

	id, _ := strconv.Atoi(c.Param("id"))
	statusCode = repositories.UpdateUser(id, user)

	if statusCode == errormsg.SUCCESS {
		statusCode = repositories.UpdateUser(id, user)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": statusCode,
		"msg":  errormsg.GetErrorMsg(statusCode),
	})
}
